package com.define.ssh.action.privilege;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import javax.annotation.Resource;

import net.sf.json.JSONArray;

import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.hibernate.Criteria;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;

import com.define.ssh.action.admin.BaseAdminAction;
import com.define.ssh.action.admin.BaseAdminAction.Status;
import com.define.ssh.model.Compdept;
import com.define.ssh.model.Deptuser;
import com.define.ssh.model.FictitiousUser;
import com.define.ssh.model.SysPower;
import com.define.ssh.model.UserInfo;
import com.define.ssh.service.CompdeptService;
import com.define.ssh.service.DeptuserService;
import com.define.ssh.service.SysPowerService;
import com.define.ssh.service.UserInfoService;
import com.define.ssh.util.InterfaceIpData;

/**
 *  
 * 
 */
@ParentPackage("admin")
public class UserPrivilegeAction extends BaseAdminAction {

	/** 页面传递参数过来 */
	protected int pageSize;
	protected int pageNum;

	@Resource(name = "sysPowerServiceImpl")
	private SysPowerService sysPowerService;

	@Resource(name = "userInfoServiceImpl")
	private UserInfoService userInfoService;

	@Resource(name = "compdeptServiceImpl")
	private CompdeptService compdeptService;

	@Resource(name = "deptuserServiceImpl")
	private DeptuserService deptuserService;

	private SysPower syspower;

	private String users;
	private String data;

	/**
	 * 列表页
	 * 
	 * @return
	 * @throws Exception
	 */
	public String list() {
		final HashMap<String, Object> searchMap = new HashMap<String, Object>();
		pager.setSearchMap(searchMap);
		pager = this.sysPowerService.findPager(pager);
		saveLog("用户权限管理", "查看列表：" + pager.getPageNumber());
		return "userPrivilege";
	}

	/**
	 * 取部门树数据
	 * @return
	 */
	public String getDeptUserTree(){
		 DetachedCriteria dt = DetachedCriteria.forClass(Compdept.class);
		 dt.add(Restrictions.eq("company.id",InterfaceIpData.compid));
		 dt.add(Restrictions.eq("pid",0));
		 dt.add(Restrictions.in("updatetype", new Object[]{1,2}));
		 List<Compdept> list = this.compdeptService.findByCriteria(dt);
		 StringBuffer sb = new StringBuffer();
		sb.append("[");
		for (int i = 0; i < list.size(); i++) {
			final Compdept dept = list.get(i);
			sb.append("{");
			sb.append("id:" + dept.getId());
			sb.append(",pId:" + dept.getPid());
			sb.append(",name:\"" + dept.getDeptname() + "\"");
			 DetachedCriteria dt1 = DetachedCriteria.forClass(Compdept.class);
			 dt1.add(Restrictions.eq("pid",dept.getId()));
			 List<Compdept> list1 = this.compdeptService.findByCriteria(dt1);
			if(list1!=null&&list1.size()>0){
				sb.append(",open:true");
				sb.append(",isParent:true");
			}
			sb.append("}");
			if (i != list.size() - 1) {
				sb.append(",");
			}
		}
		sb.append("]");
		return ajax(JSONArray.fromObject(sb.toString()).toString());
	}
	
	public String getUserListByDept() {
		try {
			
			String deptidStr = super.getRequest().getParameter("id");
			Integer deptid=null;
			if(StringUtils.isNotEmpty(deptidStr)){
				deptid=Integer.valueOf(deptidStr);
			}
			pager=this.deptuserService.find(pager, deptid, data);
			
			List<Deptuser> du_list = (List<Deptuser>) pager.getResult();
			StringBuffer sb=new StringBuffer();
			
			sb.append(",\"list\":[");
			for(Deptuser du:du_list){
				//if(du.getUserInfo().getUpdatetype()!=3&&this.getFictitiousUser(du.getUserInfo().getId(), fu_list)==null){
				if(1==1){
					if(sb.length()>10){
						sb.append(",");
					}
					sb.append("{");
					sb.append("\"id\":\""+du.getUserInfo().getId()+"\"");
					sb.append(",\"name\":\""+du.getUserInfo().getName()+"\"");
					sb.append(",\"deptName\":\""+du.getDept().getDeptname()+"\"");
					sb.append(",\"local\":\""+du.getUserInfo().getLocal()+"\"");
					sb.append("}");
				}
			}
			sb.append("]");
			
			StringBuffer sb1=new StringBuffer();
			sb1.append("{");
			sb1.append("\"pageCount\":\""+pager.getPageCount()+"\"");
			sb1.append(",\"pageNumber\":\""+pager.getPageNumber()+"\"");
			sb1.append(sb);
			sb1.append("}");
			return ajax(sb1.toString());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public String save() {
		syspower.setCompid(10);
		syspower.setEditenable(0);
		syspower.setNameformat("");
		syspower.setSyspower(1);
		syspower.setUpdatetime(new Date());
		syspower.setUpdatetype(1);
		this.sysPowerService.save(syspower);
		return ajax(Status.success, "保存成功");
	}

	public String rightShare() {
		syspower = this.sysPowerService.get(syspower.getId());

		final List<SysPower> list = sysPowerService.getAllList();

		final List<Object> id_list = new ArrayList<Object>();
		for (final SysPower sp : list) {
			id_list.add(sp.getId());
		}

		final List<List<Object>> result = UserPrivilegeAction.getCombinations(
				id_list, syspower.getId());
		final List<Integer> power_list = new ArrayList<Integer>();
		for (final List<Object> a : result) {
			int power = 0;
			for (final Object o : a) {
				final int p = (Integer) o;
				power += this.convertId(p);
			}
			power_list.add(power);
		}

		final HashMap<String, Object> searchMap = new HashMap<String, Object>();
		// searchMap.put("power", getIdsByPower(convertId(syspower.getId())));
		pager.setSearchMap(searchMap);
		pager = this.userInfoService.findPagerByPowers(pager, power_list);

		return "rightShare";
	}

	public String edit() {
		final SysPower sp = this.sysPowerService.get(syspower.getId());
		return ajax(sp);
	}

	public String update() {
		final SysPower sp = this.sysPowerService.get(syspower.getId());
		sp.setName(syspower.getName());
		sp.setDescription(syspower.getDescription());
		sp.setParameter(syspower.getParameter());
		this.sysPowerService.update(sp);
		return ajax(Status.success, "修改成功");
	}

	public String delete() {
		this.sysPowerService.delete(syspower.getId());
		return ajax(Status.success, "删除成功");
	}

	public String select() {
		syspower = this.sysPowerService.get(syspower.getId());

		final List<SysPower> list = sysPowerService.getAllList();

		final List<Object> id_list = new ArrayList<Object>();
		for (final SysPower sp : list) {
			id_list.add(sp.getId());
		}

		final List<List<Object>> result = UserPrivilegeAction.getCombinations(
				id_list, syspower.getId());
		final List<Integer> power_list = new ArrayList<Integer>();
		for (final List<Object> a : result) {
			int power = 0;
			for (final Object o : a) {
				final int p = (Integer) o;
				power += this.convertId(p);
			}
			power_list.add(power);
		}

		pager = deptuserService.findPagerByPowerList(power_list, pager);
		return "select";
	}

	public String saveUser(){
		syspower = this.sysPowerService.get(syspower.getId());
		final List<SysPower> list = sysPowerService.getAllList();
		final List<Object> id_list = new ArrayList<Object>();
		for (final SysPower sp : list) {
			id_list.add(sp.getId());
		}
		final List<List<Object>> result = UserPrivilegeAction.getCombinations(
				id_list, syspower.getId());
		final List<Integer> power_list = new ArrayList<Integer>();
		for (final List<Object> a : result) {
			int power = 0;
			for (final Object o : a) {
				final int p = (Integer) o;
				power += this.convertId(p);
			}
			power_list.add(power);
		}
		for (String userStr : data.split(",")) {
			if (!userStr.equals("")) {
				//String[] temp = userStr.split("_");
				long userid = Long.parseLong(userStr);
				final UserInfo ui = this.userInfoService.get(userid);
				final int power = ui.getPower();
				final List<Integer> old = this.getIdsByPower(power);
				boolean b = false;// 不存在
				for (final Integer o : old) {
					if (o.equals(syspower.getId())) {
						b = true;
						break;
					}
				}
				if (!b) {// 不存才操作
					int newpower = this.convertId(syspower.getId());
					for (final Integer oid : old) {
						newpower += this.convertId(oid);
					}
					ui.setPower(newpower);
					this.userInfoService.update(ui);
				}
			}
		}
		return ajax(Status.success, "操作成功");
	}

	/**
	 * 取部门树数据
	 * 
	 * @return
	 */
	public String getUserTT() {
		
		try {
			String deptid = super.getRequest().getParameter("id");
			DetachedCriteria dt1 = DetachedCriteria.forClass(Compdept.class);
			dt1.add(Restrictions.in("updatetype", new Object[]{1,2}));
			dt1.add(Restrictions.eq("company.id",InterfaceIpData.compid));
			dt1.add(Restrictions.eq("pid",Integer.valueOf(deptid)));
			List<Compdept> list = this.compdeptService.findByCriteria(dt1);
			StringBuffer sb=new StringBuffer();
			sb.append("[");
			for(int i=0;i<list.size();i++){
				Compdept dept=list.get(i);
				sb.append("{");
				sb.append("id:"+dept.getId());
				sb.append(",pId:"+dept.getPid());
				sb.append(",name:\""+dept.getDeptname()+"\"");
				Integer count=compdeptService.count(dept.getId());
				if(count>0){
					sb.append(",open:true");
					sb.append(",isParent:true");
				}
				sb.append("}");
				if(list.size()>0){
					sb.append(",");
				}
			}
			sb.append("]");
			return ajax(sb.toString());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 取部门树数据
	 * 
	 * @return
	 */
	public String getUserIds() {
		syspower = this.sysPowerService.get(syspower.getId());

		final List<SysPower> list = sysPowerService.getAllList();

		final List<Object> id_list = new ArrayList<Object>();
		for (final SysPower sp : list) {
			id_list.add(sp.getId());
		}

		final List<List<Object>> result = UserPrivilegeAction.getCombinations(
				id_list, syspower.getId());
		final List<Integer> power_list = new ArrayList<Integer>();
		for (final List<Object> a : result) {
			int power = 0;
			for (final Object o : a) {
				final int p = (Integer) o;
				power += this.convertId(p);
			}
			power_list.add(power);
		}

		final HashMap<String, Object> searchMap = new HashMap<String, Object>();
		pager.setSearchMap(searchMap);
		pager.setPageSize(100000);
		pager = this.userInfoService.findPagerByPowers(pager, power_list);
		final List<UserInfo> user_list = (List<UserInfo>) pager.getResult();
		final StringBuffer sb = new StringBuffer();
		sb.append("[");
		for (int i = 0; i < user_list.size(); i++) {
			final UserInfo ui = user_list.get(i);
			sb.append("{");
			sb.append("id:\"u" + ui.getId() + "\"");
			sb.append("}");
			if (i != user_list.size() - 1) {
				sb.append(",");
			}
		}
		sb.append("]");
		return ajax(JSONArray.fromObject(sb.toString()).toString());
	}

	public String deleteUser() {
		syspower = this.sysPowerService.get(syspower.getId());
		List<Long> list = new ArrayList<Long>();
		if (users.contains(",")) {
			for (String u : users.split(",")) {
				if (StringUtils.isNotEmpty(u)) {
					list.add(Long.parseLong(u));
				}
			}
		} else {
			list.add(Long.parseLong(users));
		}
		for (Long userid : list) {
			final UserInfo ui = this.userInfoService.get(userid);
			final List<Integer> old = this.getIdsByPower(ui.getPower());
			int newpower = 0;
			for (final Integer oid : old) {
				if (!oid.equals(syspower.getId())) {
					newpower += this.convertId(oid);
				}
			}
			ui.setPower(newpower);
			this.userInfoService.update(ui);
		}

		return ajax(Status.success, "删除成功");
	}

	public String addUser() {
		syspower = this.sysPowerService.get(syspower.getId());
		final List<SysPower> list = sysPowerService.getAllList();
		final List<Object> id_list = new ArrayList<Object>();
		for (final SysPower sp : list) {
			id_list.add(sp.getId());
		}
		final List<List<Object>> result = UserPrivilegeAction.getCombinations(
				id_list, syspower.getId());
		final List<Integer> power_list = new ArrayList<Integer>();
		for (final List<Object> a : result) {
			int power = 0;
			for (final Object o : a) {
				final int p = (Integer) o;
				power += this.convertId(p);
			}
			power_list.add(power);
		}
		for (String userStr : data.split(",")) {
			if (!userStr.equals("")) {
				//String[] temp = userStr.split("_");
				long userid = Long.parseLong(userStr);
				final UserInfo ui = this.userInfoService.get(userid);
				final int power = ui.getPower();
				final List<Integer> old = this.getIdsByPower(power);
				boolean b = false;// 不存在
				for (final Integer o : old) {
					if (o.equals(syspower.getId())) {
						b = true;
						break;
					}
				}
				if (!b) {// 不存才操作
					int newpower = this.convertId(syspower.getId());
					for (final Integer oid : old) {
						newpower += this.convertId(oid);
					}
					ui.setPower(newpower);
					this.userInfoService.update(ui);
				}
			}
		}
		return ajax(Status.success, "添加成功");
	}

	public SysPower getSyspower() {
		return syspower;
	}

	public void setSyspower(SysPower syspower) {
		this.syspower = syspower;
	}

	/**
	 * 根据power分解出id
	 * 
	 * @param num
	 * @return
	 */
	private List<Integer> getIdsByPower(int num) {
		final List<Integer> list = new ArrayList<Integer>();
		final String numStr = Integer.toBinaryString(num);// 转二进制
		final StringBuffer bf = new StringBuffer();
		for (int i = 0; i < numStr.length(); i++) {
			if (numStr.charAt(i) != '0') {
				bf.append(numStr.length() - 1 - i);
			}
		}
		final int arr[] = new int[bf.length()];
		for (int i = 0; i < bf.length(); i++) {
			arr[i] = bf.charAt(i) - '0';
			list.add(arr[i] + 1);
		}
		return list;
	}

	private int convertId(int id) {
		return (int) Math.pow(2, id - 1);
	}

	private static List<List<Object>> getCombinations(List<Object> list,
			Object o) {
		final List<List<Object>> result = new ArrayList<List<Object>>();
		final long n = (long) Math.pow(2, list.size());
		List<Object> combine;
		for (long l = 0L; l < n; l++) {
			combine = new ArrayList<Object>();
			for (int i = 0; i < list.size(); i++) {
				if ((l >>> i & 1) == 1)
					combine.add(list.get(i));
			}
			for (final Object obj : combine) {
				if (obj.equals(o)) {
					result.add(combine);
				}
			}
		}
		return result;
	}

	public String getUsers() {
		return users;
	}

	public void setUsers(String users) {
		this.users = users;
	}

	public String getData() {
		return data;
	}

	public void setData(String data) {
		this.data = data;
	}

}